﻿/*

Copyright (c) 2009, Stephen Remde
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY STEPHEN REMDE ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL STEPHEN REMDE BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


*/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Graphs;
using WikiMiner;
using System.Threading;

namespace WindowsFormsApplication1
{
    public partial class ExploreVisualisation : Form
    {
        float relAdd, relLink;

        Graph g;

        public ExploreVisualisation(Article from)
            : this(from, 0.8f, 0.7f)
        {

        }

        bool running = true;

        public ExploreVisualisation(Article from, float relAdd, float relLink)
            : this()
        {
            this.relAdd = relAdd;
            this.relLink = relLink;
            this.g = new Graph();

            Text = string.Format("Exploring '{0}'", from.title);

            ThreadPool.QueueUserWorkItem(new WaitCallback(DoExpand), from);
        }

        public ExploreVisualisation()
        {
            InitializeComponent();
        }

        public class WikiVisLink : Link
        {
            public float rel;
        }

        public class WikiVisNode : Node
        {
            public float g;
        }


        private void DoExpand(object o)
        {
            Article From = o as Article;

            List<Candidate> open = new List<Candidate>();
            List<Article> closed = new List<Article>();

            open.Add(new Candidate() { article = From,  parent = null });

            {
                Node n = new WikiVisNode() { text = From.title, fixedinplace = true };
                n.x = Width / 2;
                n.y = Height / 2;

                g.AddNode(n);
            }

            int its = 0;
            while (open.Count > 0 && running)
            {
                its++;
                var ord = open.OrderBy(item => item.G);
                Random r = new Random();
                Candidate at = ord.Skip((int)((0.05 + 0.95 * r.NextDouble() * r.NextDouble() * r.NextDouble() * r.NextDouble()) * ord.Count())).First();

                closed.Add(at.article);
                open.Remove(at);

                Node node_at = g.GetNode(at.article.title);

                node_at.visible = true;

                if (at.parent != null)
                {
                    g.GetLink(node_at, g.GetNode(at.parent.article.title)).visible = true;

                }

                Recolour();




               
                Thread.Sleep(1000);

                int added = 0;

                foreach (var link in Links.GetOutLinks(at.article.id).OrderBy(a => -Relatedness.Get(a.title, at.article.title)))
                {
                    float rel = Relatedness.Get(at.article.title, link.title);
                    
                    Node node_to = g.GetNode(link.title);

                    if (node_to == null )
                    {
                        node_to = new WikiVisNode() { text = link.title, visible = false };
                        g.AddNode(node_to, node_at);
                    }

                    if (rel > relAdd && added++ < 5)
                        node_to.visible = true;

                    Link l = g.AddLink(new WikiVisLink() { a = node_at, b = node_to, visible = false, rel = rel });
                    l.AddArrowTo(node_to);
                    l.text = rel.ToString("0%");
                    l.width = 10 * rel;

                    if (rel > relLink && node_to.visible)
                    {
                        l.visible = true;
                    }




                    if (!closed.Exists(item => item.id == link.id))
                    {
                        Candidate existing = open.FirstOrDefault(item => item.article.id == link.id);

                        if (existing != null)
                        {
                            existing.UpdateParentIfBetter(at);
                        }
                        else
                        {
                            existing = new Candidate()
                            {
                                article = link,
                                parent = at
                            };
                            open.Add(existing);
                        }

                        (node_to as WikiVisNode).g = existing.G;
                    }

                }

            }

            Relatedness.Save();
        }
        class Candidate
        {
            public Article article;

            public float G;


            private Candidate _parent = null;

            public Candidate parent
            {
                set
                {
                    _parent = value;
                    if (value == null)
                    {
                        G = 0;
                    }
                    else
                    {
                        G = _parent.G + 1 - Relatedness.Get(article.title, _parent.article.title);                        
                    }
                }
                get
                {
                    return _parent;
                }
            }

            internal void UpdateParentIfBetter(Candidate newparent)
            {
                if (_parent != null)
                {
                    if (_parent.G + 1 - Relatedness.Get(article.title, newparent.article.title) < G)
                    {
                        parent = newparent;
                    }
                }
            }
        }


        private void timer1_Tick(object sender, EventArgs e)
        {
            Refresh();
        }

        private void ExploreVisualisation_Paint(object sender, PaintEventArgs e)
        {
            g.Organize(1);
            g.AutoAdjustViewport((float)ClientSize.Width, (float)ClientSize.Height, 0);
            g.Draw(e.Graphics, false);
        }

        private void ExploreVisualisation_FormClosing(object sender, FormClosingEventArgs e)
        {
            running = false;
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            Recolour();
        }

        private void Recolour()
        {

            float maxg = 1;
                foreach (var n in g.GetNodes())
                {
                    float t = (n as WikiVisNode).g;

                    if (t > maxg)
                        maxg = t;
                }
            
            foreach (var n in g.GetNodes())
            {
                float t = (n as WikiVisNode).g;
                int gg = (int)(255 * t / maxg);
                if (gg > 255) gg = 255;
                n.color = Color.FromArgb(0, 255 - gg, gg);
            }

            foreach (var l in g.GetLinks())
            {
                l.color = Color.LightBlue;
                if (checkBox1.Checked)
                {
                    l.text = (l as WikiVisLink).rel.ToString("0.0%");
                }
                else
                {
                    l.text = null;
                }
            }
        }

        private void ExploreVisualisation_Load(object sender, EventArgs e)
        {

        }

        private void ExploreVisualisation_Click(object sender, EventArgs e)
        {
            /*
            Bitmap b = new Bitmap(9810, 13620);
            Graphics gr = Graphics.FromImage(b);
            g.Viewport.Zoom = 3;
            g.Draw(gr, true);
            b.Save("c:\\temp.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
             * */
        }

    }
}
